package day3;

import day2.dao.IDeptDao;
import day2.dao.IEmpDao;
import day2.entity.Emp;
import org.apache.ibatis.session.SqlSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import util.Util;

import java.util.List;

public class MyCache {
    SqlSession session;
    IDeptDao deptDao;
    IEmpDao empDao;
    @Before
    public void init(){
        session= Util.getSession();
        deptDao=session.getMapper(IDeptDao.class);
        empDao=session.getMapper(IEmpDao.class);
    }
    @After
    public void close(){
        session.commit();
        session.close();
    }

    @Test
    public void oneLevel() throws InterruptedException {
        List<Emp>list= empDao.selectEmpByDeptId(15);
        Thread.sleep(5000);
        //session.clearCache();会清空一级缓存
        //empDao.insertEmp(new Emp());增删改会清空一二级缓存
        empDao.selectEmpByDeptId(15);
        //list= Util.getSession().getMapper(IEmpDao.class).selectEmpByDeptId(15);
        System.out.println(list);
    }

    public static void main(String[]args) throws InterruptedException {
        for(int i=0;i<3;i++){
            new Thread("线程"+i){
                public void run() {
                    SqlSession s=Util.getSession();
                    IEmpDao dao=s.getMapper(IEmpDao.class);
                    System.out.println(Thread.currentThread().getName()+":"+dao.selectEmpByDeptId(15));
                    s.commit();//必须提交，否则不会把数据存入到缓存中.
                }
            }.start();
            try {
                Thread.sleep(2000);
                if(i==0){
                    SqlSession s=Util.getSession();
                    IEmpDao dao=s.getMapper(IEmpDao.class);
                    dao.insertEmp(new Emp());
                    s.commit();
                }
            } catch (InterruptedException e) {}
        }

        //Thread.sleep(5000);
    }
}
